<?php

namespace App\Logic\Auth;

use App\Core\BaseCore;
use App\Core\Exception\DefaultException;
use App\Core\Output;
use App\Model\Auth\MenuModel;
use App\Model\Auth\MenuRoleModel;
use App\Model\Auth\RoleModel;
use App\Model\UserModel;
use App\Util\ArrayHelper;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Component\Singleton;
use EasySwoole\ORM\Exception\Exception;
use Throwable;

class RoleService extends BaseCore
{

    use Singleton;

    /**
     * 字典数据
     * @return Output
     * @throws Exception
     * @throws Throwable
     */
    public function getDict(): Output
    {
        $menu_model = new MenuModel();
        $list = $menu_model->getLists();
        $list = CommonHelper::listToTree($list,'id','pid','child');
    
        //当用户角色为非管理员
        $userIdentity = UserIdentityHelper::getIdentity();
        $type_list = RoleModel::getTypeDict();
        if ( $userIdentity->type <> UserModel::TYPE_INSIDE ){
            unset($type_list[RoleModel::TYPE_INSIDE]);
        }
//        unset($type_list[RoleModel::TYPE_INSIDE]);
        $result = [
            'menu_list' => $list,
            'type_list' => ArrayHelper::keyArrayToList($type_list),
        ];
        
        return $this->success($result);
    }

    /**
     * 删除记录
     * @param $selected
     * @return Output
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws Exception
     * @throws Throwable
     */
    public function deleteRecord($selected) : Output{
        is_array($selected) or $selected = [$selected];

        if ( UserModel::getCount(['role_id'=>$selected]) >0 ){
            throw new DefaultException('该角色已经被使用，无法删除');
        }

        $result = RoleModel::deleteRecord(['id' => $selected]);
        if($result < 1){
            throw new DefaultException('操作失败');
        }

        return $this->success(['affectedRows'=>$result]);
    }

    /**
     * 详情数据
     * @param $id
     * @return Output
     * @throws DefaultException
     * @throws Exception
     * @throws Throwable
     */
    public function getInfo($id): Output
    {
        if ( empty($id) ){
            throw new DefaultException('参数错误');
        }

        $result = [];

        //查询有权限的菜单id
        $menu_ids = MenuRoleModel::makeQueryModel(['role_id'=>$id])->column('menu_id');
        $result['menu_ids'] = $menu_ids;

        return $this->success($result);
    }


}